/*
 * SQLListBox.java
 *
 * Created on December 4, 2006, 2:55 PM
 */

package org.foment.joliage3.newt;

import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultListModel;
import javax.swing.event.ListSelectionEvent;
import org.foment.joliage3.sql.Database;
import org.foment.joliage3.sql.Table;

/**
 *
 * @author  jaksa
 */
public class SQLListBox extends javax.swing.JList implements java.io.Serializable, org.foment.joliage3.sql.Table.TableListener {
    
    /** Creates new form BeanForm */
    public SQLListBox() {
        initComponents();
        
        addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //System.out.println("Clicked: " + getSelectedIndex());
               listener();
            }
        });
    }
    
    /**
     * Getter for property tableName.
     * @return Value of property tableName.
     */
    public String getTableName() {
        return _tableName;
     }

    public void listener()
    {
        if (getSelectedIndex() != -1)
        {
            KeyValue kv = (KeyValue) getSelectedValue();
            if (kv != null)
                _currentKey = kv.getKey();
            else _currentKey = -1; 
        }
        else
            _currentKey = -1;
    }

    /**
     * Setter for property tableName.
     * @param tableName New value of property tableName.
     */
    public void setTableName(String tableName) {
        _tableName = tableName;
        readData();
    }
    
    /**
     * Getter for property keyName.
     * @return Value of property keyName.
     */
    public String getKeyName() {
        return _keyName;
    }

    /**
     * Setter for property keyName.
     * @param keyName New value of property keyName.
     */
    public void setKeyName(String keyName) {
        _keyName = keyName;
        readData();
    }

    /**
     * Getter for property fieldName.
     * @return Value of property fieldName.
     */
    public String getFieldName() {
        return _fieldName;
    }

    /**
     * Setter for property fieldName.
     * @param fieldName New value of property fieldName.
     */
    public void setFieldName(String fieldName) {
        _fieldName = fieldName;
        readData();
    }
    
    public void setQuery(String query)
    {
        _query = query;
        readData();
    }
    
    public String getQuery()
    {
        return _query;
    }
    
    public void listenTables(String[] tables) {
      Table.removeListenerFromAll(this);
      for (String tableName: tables) {
       try {
          Database.getTable(tableName).addListener(this);
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }

    public void listenTables(String tables) {
      listenTables(tables.split(", *"));
    }
    
    /** 
     * fetches data from database
     */    
    private void readData()
    {
        if (_tableName != null && _keyName != null && _fieldName != null) {
          _query = "SELECT " + _keyName + " AS keyName, " + _fieldName + " AS fieldName FROM " + _tableName + ";";
          listenTables(_tableName);
        }
        
        if (_query == null)
            return ;

        _elements.clear();
        int index = -1;
        //_currentKey = -1; // to sam ja dodao. treba ispitati!
        try
        {
            Connection conn = Database.getConnection();
            ResultSet rs = conn.createStatement().executeQuery(_query);

            for (int i = 0; rs.next(); i++)
            {
                int key      = rs.getInt("keyName");
                String value = rs.getString("fieldName");
                
                if (_currentKey == key)
                    index = i;
                _elements.addElement(new KeyValue(key, value));
                //System.out.println("Dodato: " + value + key);
            }

            rs.close();
            conn.close();
        } catch (SQLException ex)
        { ex.printStackTrace(); }
        
        setModel(_elements);
        
        if (index != -1)
            setSelectedIndex(index);
    }
    
    public int getValue()
    {
        return _currentKey;
    }
  
    public void setValue(int key) 
    {
        _currentKey = key;
        readData();
    }
    
    public void refresh()
    {
        readData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    public void tableRowDeleted(Table table, int row) {
        readData();
    }

    public void tableRowUpdated(Table table, int row) {
        readData();
    }

    public void tableRowInserted(Table table) {
        readData();
    }

    public void tableDataChanged(Table table) {
        readData();
    }
    
    private DefaultListModel _elements = new DefaultListModel();
    private String _query;
    private String _keyName;
    private String _fieldName;
    private String _tableName;
    private int _currentKey = -1;
}
